package com.propertree.mailer.helper;

import java.util.Date;
import java.util.Map;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.propertree.mailer.bean.EMailPartyInfo;
import com.propertree.mailer.bean.EmailAttributes;

public final class MessageDecorator {

	private static Multipart multipart = null;

	private MessageDecorator() {
	}

	public static Message createMessage(Session session, EMailPartyInfo senderParty, EMailPartyInfo receiverParty,
			EmailAttributes email) {
		Message message = new MimeMessage(session);
		try {
			message.setFrom(new InternetAddress(senderParty.getEmailId()));
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiverParty.getEmailId()));
			message.setSubject(email.getSubject());
			message.setContent(email.getBody(), "text/html");
			message.setSentDate(new Date());
			message.setReplyTo(new Address[] { new InternetAddress(senderParty.getEmailId()) });

			if (multipart == null) {
				initMultiMediaMsg(email.getAttachments());
			}

			if (multipart != null){
				message.setContent(multipart);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return message;
	}

	private static void initMultiMediaMsg(Map<String, String> attachments) throws Exception {
		if (attachments == null || attachments.isEmpty()) {
			return;
		}
		multipart = new MimeMultipart();

		String fileName = "";
		String filePath = "";
		for (Map.Entry<String, String> attachmentFile : attachments.entrySet()) {
			fileName = attachmentFile.getKey();
			filePath = attachmentFile.getValue();
			if (fileName.trim() != "" && filePath.trim() != "") {
				MimeBodyPart messageBodyPart = new MimeBodyPart();
				messageBodyPart.attachFile(filePath);
				messageBodyPart.setFileName(fileName);
				multipart.addBodyPart(messageBodyPart);
			}
		}
	}
}
